﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using Runda.CMS.Common.Entity;
using Runda.CMS.Bll;
using Runda.CMS.Common.Utility;
using System.Collections.Generic;
using Runda.CMS.Workflow;
using System.Text;
using Runda.CMS.Common.Exchange;

namespace Runda.CMS.Portal.ContractManage
{
    public partial class ContractView :BasePage
    {
        public Guid ContractID
        {
            get
            {
                if (txtContractID.Value == string.Empty) return Guid.Empty;
                else return new Guid(txtContractID.Value);
            }
            set
            {
                txtContractID.Value = value.ToString();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckTabPermission();

                listContractType.BindEnum(EnumeratorHelper.GetFieldTexts(typeof(Enumerator.ContractType)));

                List<SqlDbParameter> parms = new List<SqlDbParameter>();
                SqlDbParameter parm = new SqlDbParameter();
                parm.ColumnName = "Type";
                parm.ColumnType = DbType.Int32;
                parm.ParameterName = "@Type";
                parm.ParameterValue = System.Convert.ToInt32(ContractEnumerator.ContractParms.contractAttr);
                parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
                parms.Add(parm);
                listContractAttribute.DataSource = new SysDictionaryBll().GetAll<SysDictionaryEntity>(parms);
                listContractAttribute.DataTextField = "Code";
                listContractAttribute.DataValueField = "ID";
                listContractAttribute.DataBind();
                if (Request.QueryString["ContractID"] != null)
                {
                    ContractID = new Guid(Request.QueryString["ContractID"]);
                    InitForm();

                    //LoadItem();
                } 
            }
        }

        private void InitForm()
        {
            CtrtContractEntity entity = new CtrtContractEntity();
            CtrtContractBll bll = new CtrtContractBll();

            if (ContractID != Guid.Empty)
            {
                entity = bll.Get<CtrtContractEntity>(ContractID);
                txtContractCode.Text = entity.ContractCode;
                listContractAttribute.SelectedValue = entity.ContractAttribute.ToString();

                if (entity.ContractApplyDate != DateTime.MinValue)
                    txtContractApplyDate.SelectedDate = entity.ContractApplyDate;

                if (entity.ContractEstimateSignDate != DateTime.MinValue)
                    txtContractEstimateSignDate.SelectedDate = entity.ContractEstimateSignDate;

                listContractType.SelectedValue = entity.ContractType;
                txtContractStatement.Text = entity.ContractStatement;
                //txtContractPeriod.Text = entity.ContractPeriod.ToString();
                //txtGivenMaterialdesc.Text = entity.GivenMaterialdesc;
                //txtGivenMaterialCost.Text = entity.GivenMaterialCost.ToString();
                //txtCapitalCost.Text = entity.CapitalCost.ToString();
                radtxtReachTo.Value = (double)entity.ReachTo;
                radtxtRebate.Value = (double)entity.Rebate;

                if (entity.CustomerID != Guid.Empty)
                {
                    CtrtCustomerEntity userEntity = new CtrtCustomerBll().Get<CtrtCustomerEntity>(entity.CustomerID);
                    hiddenuserName.InnerText = userEntity.CustomerName;
                    hiddenUserID.Value = userEntity.CustomerID.ToString();
                }

                listContractType.Enabled = false;

                if (entity.InstanceID != Guid.Empty)
                {
                    BindWorkflow(entity.InstanceID);
                }

                //合同变更信息
                if (entity.OriginalContractID != Guid.Empty)
                {
                    txtChangeRemark.Text = entity.ChangeRemark;
                    lnkOrginalContract.NavigateUrl = "ContractAdd.aspx?ContractID=" + entity.OriginalContractID;
                }
                else
                {
                    ltlChangeTitle.Visible = false;
                    pnlChange.Visible = false;
                }

            } 
        }

        private void CheckTabPermission()
        {
            SystemBll bll = new SystemBll();

            //检查利润预算权限
            if (!bll.CheckUserHasFuction(base.CurrentUserID, 0, "ContractManage/ContractProfitSale.aspx"))
            {
                divTarget.Visible = false;
            }
            else
            { divTarget.Visible = true; }

            if (!bll.CheckUserHasFuction(base.CurrentUserID, 0, "ContractManage/ContractProfitPut.aspx"))
            {
                divTarget.Visible = false;
            }
            else
            { divTarget.Visible = true; }

            if (!bll.CheckUserHasFuction(base.CurrentUserID, 0, "ContractManage/ContractDocument.aspx"))
            {
                divDocument.Visible = false;
            }
            else
            { divDocument.Visible = true; }
        }

        protected void lnkbtnSave_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandcloseerror", "alert('" + Message + "');", true);
            }
            else
                ClientScript.RegisterStartupScript(this.GetType(), "save", "alert('保存成功');", true);
        }

        protected void lnkbtnSaveAndClose_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveandssscloseerror", "alert('" + Message + "');", true);
            }
            else
                ClientScript.RegisterStartupScript(this.GetType(), "saveandclose", "window.close();", true);
        }

        protected void lnkbtnSaveAndNew_Click(object sender, EventArgs e)
        {
            string Message = "";
            if (!Save(ref Message))
            {
                ClientScript.RegisterStartupScript(this.GetType(), "saveansrror", "alert('" + Message + "');", true);
            }
            else
            {
                ContractID = Guid.Empty;
                txtContractCode.Text = "";
                txtContractApplyDate.SelectedDate = null;
                txtContractEstimateSignDate.SelectedDate = null;
                txtContractStatement.Text = "";
                //txtContractPeriod.Text = "";
                //txtGivenMaterialdesc.Text = "";
                //txtGivenMaterialCost.Text = "";
                //txtCapitalCost.Text = "";
                ClientScript.RegisterStartupScript(this.GetType(), "saveandnew", "alert('保存成功');", true);
            }
        }

        private bool Save(ref string Message)
        {
            CtrtContractBll bll = new CtrtContractBll();
            CtrtContractEntity entity = new CtrtContractEntity();

            //check contract code 唯一性
            if (ContractID != Guid.Empty) //编辑状态
            {
                entity = bll.Get<CtrtContractEntity>(" and ContractID != '" + ContractID + "' and ContractCode = '" + txtContractCode.Text + "'");
                if (entity != null)
                {
                    Message = "合同编号已存在!";
                    return false;
                }
            }
            else //新增状态
            {
                entity = bll.Get<CtrtContractEntity>(" and ContractCode = '" + txtContractCode.Text + "'");
                if (entity != null)
                {
                    Message = "合同编号已存在!";
                    return false;
                }
            }

            //try save info
            if (ContractID != Guid.Empty)
            {
                entity = bll.Get<CtrtContractEntity>(ContractID);
            }
            else
            {
                entity = new CtrtContractEntity();
                ContractID = entity.ContractID;
                entity.CreatedBy = CurrentUserID;
                entity.CreatedOn = DateTime.Now;

                entity.Status = (int)Enumerator.ContractStatus.Draft;
            }

            if (hiddenUserID.Value != string.Empty)
                entity.CustomerID = new Guid(hiddenUserID.Value);
            entity.ContractCode = txtContractCode.Text;
            if (listContractAttribute.SelectedValue != string.Empty)
                entity.ContractAttribute = new Guid(listContractAttribute.SelectedValue);
            if (txtContractApplyDate.SelectedDate.HasValue)
                entity.ContractApplyDate = txtContractApplyDate.SelectedDate.Value;
            if (txtContractEstimateSignDate.SelectedDate.HasValue)
                entity.ContractEstimateSignDate = txtContractEstimateSignDate.SelectedDate.Value;
            entity.ContractType = listContractType.SelectedValue;
            entity.ContractStatement = txtContractStatement.Text;
            //if(txtContractPeriod.Text != string.Empty)
            //    entity.ContractPeriod = Convert.ToInt32(txtContractPeriod.Text);
            //entity.GivenMaterialdesc = txtGivenMaterialdesc.Text;
            //if (txtGivenMaterialCost.Text != string.Empty)
            //    entity.GivenMaterialCost = Convert.ToDecimal(txtGivenMaterialCost.Text);
            //if(txtCapitalCost.Text != string.Empty)
            //    entity.CapitalCost = Convert.ToDecimal(txtCapitalCost.Text);

            bll.InsertOrUpdate(entity);

            txtContractID.Value = ContractID.ToString();
            listContractType.Enabled = false;

            if (entity.CustomerID != Guid.Empty)
            {
                CtrtCustomerEntity userEntity = new CtrtCustomerBll().Get<CtrtCustomerEntity>(entity.CustomerID);
                hiddenuserName.InnerText = userEntity.CustomerName;
                hiddenUserID.Value = userEntity.CustomerID.ToString();
            } 
            return true;
        }

        private void LoadItem()
        {
            if (ContractID == Guid.Empty) return;

            List<SqlDbParameter> parms = new List<SqlDbParameter>();
            SqlDbParameter parm = null;

            parm = new SqlDbParameter();
            parm.ColumnName = "ContractID";
            parm.ColumnType = DbType.Guid;
            parm.ParameterName = "@ContractID";
            parm.ParameterValue = ContractID;
            parm.QualificationType = SqlDbParameter.QualificationSymbol.Equal;
            parms.Add(parm);

            List<CtrtContractItemEntity> list = new CtrtContractItemBll().GetAll<CtrtContractItemEntity>(parms);

            //RepeaterContractItem.DataSource = list;
            //RepeaterContractItem.DataBind();
        }

        protected void RepeaterContractItem_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "refersh")
            {
                LoadItem();
            }
        }
 
 

        public string GetStatusText(int status)
        {
            string text = string.Empty;
            EnumeratorHelper[] cs = EnumeratorHelper.GetFieldTexts(typeof(Runda.CMS.Workflow.ActivityStatus));
            foreach (EnumeratorHelper c in cs)
            {
                if (c.EnumValue == status)
                {
                    text = c.EnumDisplayText; break;
                }
            }

            return text;
        }

        private void BindWorkflow(Guid InstanceID)
        {
            List<WflInstanceRoutingEntity> list = new WflInstanceRoutingBll().GetAll<WflInstanceRoutingEntity>(" and InstanceID = '" + InstanceID + "' and CheckStatus != 1 order by CheckDate");

            RepeaterApprove.DataSource = list;
            RepeaterApprove.DataBind();
        }        
    }
}
